{% extends "admin/layout.html" %}

{% block title %}门禁操作日志 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题和操作区域 -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
        <div>
            <h1 class="h3 mb-0 text-gray-800 fw-bold">
                <i class="fas fa-history me-2 text-primary"></i>门禁操作日志
            </h1>
            <p class="text-muted mb-0">查看所有门禁设备的操作历史记录</p>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-primary btn-sm" id="refreshLogs">
                <i class="fas fa-sync-alt me-1"></i>刷新
            </button>
            <button class="btn btn-outline-secondary btn-sm" id="exportLogs">
                <i class="fas fa-file-export me-1"></i>导出
            </button>
            <button class="btn btn-outline-secondary btn-sm" id="clearLogs">
                <i class="fas fa-trash-alt me-1"></i>清空日志
            </button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="text-muted small">总操作次数</div>
                            <div class="h4 font-weight-bold text-primary">{{ logs|length }}</div>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-list-alt fa-2x text-primary opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="text-muted small">成功操作</div>
                            <div class="h4 font-weight-bold text-success">{{ success_count|default(0) }}</div>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-check-circle fa-2x text-success opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="text-muted small">失败操作</div>
                            <div class="h4 font-weight-bold text-danger">{{ failed_count|default(0) }}</div>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-times-circle fa-2x text-danger opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card stat-card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="text-muted small">今日操作</div>
                            <div class="h4 font-weight-bold text-info">{{ today_count|default(0) }}</div>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-calendar-day fa-2x text-info opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选条件卡片 -->
    <div class="card shadow-sm mb-4 border-0">
        <div class="card-header py-3 bg-white d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-filter me-2"></i>筛选条件
            </h6>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#filterCollapse">
                <i class="fas fa-chevron-down"></i>
            </button>
        </div>
        <div class="collapse show" id="filterCollapse">
            <div class="card-body p-3">
                <form id="filterForm" class="row g-3">
                    <div class="col-md-2 col-6">
                        <label for="action_type" class="form-label small mb-1">操作类型</label>
                        <select class="form-select form-select-sm" id="action_type" name="action_type">
                            <option value="">全部类型</option>
                            <option value="test_connection">测试连接</option>
                            <option value="remote_open">远程开门</option>
                            <option value="remote_restart">设备重启</option>
                            <option value="sync_users">用户同步</option>
                            <option value="sync_attendance">考勤同步</option>
                        </select>
                    </div>
                    <div class="col-md-2 col-6">
                        <label for="result" class="form-label small mb-1">操作结果</label>
                        <select class="form-select form-select-sm" id="result" name="result">
                            <option value="">全部结果</option>
                            <option value="success">成功</option>
                            <option value="failed">失败</option>
                        </select>
                    </div>
                    <div class="col-md-3 col-6">
                        <label for="start_date" class="form-label small mb-1">开始日期</label>
                        <input type="date" class="form-control form-control-sm" id="start_date" name="start_date">
                    </div>
                    <div class="col-md-3 col-6">
                        <label for="end_date" class="form-label small mb-1">结束日期</label>
                        <input type="date" class="form-control form-control-sm" id="end_date" name="end_date">
                    </div>
                    <div class="col-md-2 col-12 d-flex align-items-end">
                        <div class="d-flex w-100 gap-2">
                            <button type="submit" class="btn btn-sm btn-primary flex-grow-1">
                                <i class="fas fa-filter me-1"></i>筛选
                            </button>
                            <button type="reset" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-undo"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 日志列表卡片 -->
    <div class="card shadow-sm border-0">
        <div class="card-header py-3 bg-white d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center">
            <div>
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-list me-2"></i>操作日志列表
                </h6>
                <div class="d-flex align-items-center mt-2">
                    <span class="badge bg-primary me-2">{{ logs|length }} 条记录</span>
                    <span class="text-muted small">最后更新: {{ last_updated|default('刚刚') }}</span>
                </div>
            </div>
            <div class="d-flex gap-2 mt-2 mt-md-0">
                <div class="input-group input-group-sm" style="width: 250px;">
                    <span class="input-group-text bg-light"><i class="fas fa-search"></i></span>
                    <input type="text" class="form-control" placeholder="搜索日志..." id="searchLogs">
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            {% if logs %}
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="logsTable">
                    <thead class="table-light">
                        <tr>
                            <th class="text-nowrap">
                                <i class="fas fa-clock me-1 text-muted"></i>时间
                            </th>
                            <th class="text-nowrap">
                                <i class="fas fa-user me-1 text-muted"></i>操作人员
                            </th>
                            <th class="text-nowrap">
                                <i class="fas fa-door-closed me-1 text-muted"></i>设备
                            </th>
                            <th class="text-nowrap">
                                <i class="fas fa-cog me-1 text-muted"></i>操作类型
                            </th>
                            <th class="text-nowrap">
                                <i class="fas fa-check-circle me-1 text-muted"></i>操作结果
                            </th>
                            <th class="text-nowrap">
                                <i class="fas fa-network-wired me-1 text-muted"></i>IP地址
                            </th>
                            <th>
                                <i class="fas fa-info-circle me-1 text-muted"></i>详细信息
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for log in logs %}
                        <tr>
                            <td class="text-nowrap">
                                <small class="text-muted">{{ log.created_at.strftime('%Y-%m-%d %H:%M:%S') if log.created_at is not string else log.created_at }}</small>
                            </td>
                            <td>
                                {% if log.user_name %}
                                <div class="fw-medium">{{ log.user_name }}</div>
                                {% else %}
                                <span class="text-muted small">未知用户</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if log.device_name %}
                                <div class="fw-medium">{{ log.device_name }}</div>
                                {% else %}
                                <span class="text-muted small">设备已删除</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if log.action == 'test_connection' %}
                                <span class="badge bg-secondary bg-opacity-75">
                                    <i class="fas fa-plug me-1"></i>测试连接
                                </span>
                                {% elif log.action == 'remote_open' %}
                                <span class="badge bg-info bg-opacity-75">
                                    <i class="fas fa-door-open me-1"></i>远程开门
                                </span>
                                {% elif log.action == 'remote_restart' %}
                                <span class="badge bg-warning bg-opacity-75">
                                    <i class="fas fa-redo me-1"></i>设备重启
                                </span>
                                {% elif log.action == 'sync_users' %}
                                <span class="badge bg-success bg-opacity-75">
                                    <i class="fas fa-users me-1"></i>用户同步
                                </span>
                                {% elif log.action == 'sync_attendance' %}
                                <span class="badge bg-primary bg-opacity-75">
                                    <i class="fas fa-user-clock me-1"></i>考勤同步
                                </span>
                                {% else %}
                                <span class="badge bg-secondary bg-opacity-75">{{ log.action }}</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if log.result == 'success' %}
                                <span class="badge bg-success bg-opacity-75">
                                    <i class="fas fa-check me-1"></i>成功
                                </span>
                                {% else %}
                                <span class="badge bg-danger bg-opacity-75">
                                    <i class="fas fa-times me-1"></i>失败
                                </span>
                                {% endif %}
                            </td>
                            <td>
                                <span class="small text-truncate d-inline-block" style="max-width: 120px;">
                                    <i class="fas fa-map-marker-alt me-1 text-muted"></i>{{ log.ip_address }}
                                </span>
                            </td>
                            <td>
                                {% if log.details %}
                                <div class="log-details small">
                                    {{ log.details }}
                                </div>
                                {% else %}
                                <span class="text-muted small">无详情</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% else %}
            <div class="text-center py-5">
                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                <h5 class="text-muted mb-1">暂无日志数据</h5>
                <p class="text-muted small">没有找到符合条件的门禁操作日志</p>
            </div>
            {% endif %}
        </div>
        {% if logs and logs|length > 10 %}
        <div class="card-footer bg-white py-3">
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small">
                    显示 <strong>{{ logs|length }}</strong> 条记录
                </div>
                <nav aria-label="日志分页">
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item disabled">
                            <a class="page-link" href="#" tabindex="-1">上一页</a>
                        </li>
                        <li class="page-item active"><a class="page-link" href="#">1</a></li>
                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                        <li class="page-item">
                            <a class="page-link" href="#">下一页</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- 清空日志确认模态框 -->
<div class="modal fade" id="clearLogsModal" tabindex="-1" aria-labelledby="clearLogsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="clearLogsModalLabel">
                    <i class="fas fa-exclamation-triangle text-warning me-2"></i>确认清空日志
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要清空所有门禁操作日志吗？此操作不可恢复。</p>
                <div class="alert alert-warning mb-0" role="alert">
                    <i class="fas fa-info-circle me-2"></i>清空后，所有操作记录将被永久删除。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmClearLogs">确认清空</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 刷新日志
    document.getElementById('refreshLogs').addEventListener('click', function() {
        const btn = this;
        const icon = btn.querySelector('i');

        // 添加旋转动画
        icon.classList.add('fa-spin');
        btn.disabled = true;

        setTimeout(() => {
            location.reload();
        }, 500);
    });

    // 导出日志
    document.getElementById('exportLogs').addEventListener('click', function() {
        showToast('正在准备导出数据...', 'info');
        // 模拟导出过程
        setTimeout(() => {
            showToast('数据导出完成！', 'success');
        }, 1500);
    });

    // 清空日志
    document.getElementById('clearLogs').addEventListener('click', function() {
        const clearModal = new bootstrap.Modal(document.getElementById('clearLogsModal'));
        clearModal.show();
    });

    // 确认清空日志
    document.getElementById('confirmClearLogs').addEventListener('click', function() {
        showToast('正在清空日志...', 'info');
        // 模拟清空过程
        setTimeout(() => {
            showToast('日志清空完成！', 'success');
            // 关闭模态框
            const clearModal = bootstrap.Modal.getInstance(document.getElementById('clearLogsModal'));
            clearModal.hide();
            // 刷新页面
            setTimeout(() => {
                location.reload();
            }, 1000);
        }, 1500);
    });

    // 搜索日志
    document.getElementById('searchLogs').addEventListener('input', function(e) {
        const searchTerm = e.target.value.toLowerCase();
        const rows = document.querySelectorAll('#logsTable tbody tr');

        let visibleCount = 0;
        rows.forEach(row => {
            const rowText = row.textContent.toLowerCase();
            const isVisible = rowText.includes(searchTerm);
            row.style.display = isVisible ? '' : 'none';
            if (isVisible) visibleCount++;
        });

        // 更新显示记录数
        const badge = document.querySelector('.badge.bg-primary');
        if (badge) {
            badge.textContent = `${visibleCount} 条记录`;
        }
    });

    // 筛选表单提交
    document.getElementById('filterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        showToast('正在应用筛选条件...', 'info');

        // 模拟筛选过程
        setTimeout(() => {
            showToast('筛选完成！', 'success');
        }, 1000);
    });

    // 重置筛选表单
    document.querySelector('button[type="reset"]').addEventListener('click', function() {
        showToast('筛选条件已重置', 'info');
    });

    // Toast提示函数
    function showToast(message, type = 'info') {
        const toastElement = document.getElementById('operationToast');
        const toastBody = document.getElementById('toastBody');
        const toastIcon = document.getElementById('toastIcon');

        // 设置图标和颜色
        let iconClass = 'fas fa-info-circle';
        let bgClass = 'bg-primary';

        if (type === 'success') {
            iconClass = 'fas fa-check-circle';
            bgClass = 'bg-success';
        } else if (type === 'warning') {
            iconClass = 'fas fa-exclamation-triangle';
            bgClass = 'bg-warning';
        } else if (type === 'error') {
            iconClass = 'fas fa-times-circle';
            bgClass = 'bg-danger';
        }

        toastIcon.className = iconClass + ' me-2';
        toastElement.className = 'toast ' + bgClass + ' text-white';
        toastBody.textContent = message;

        const toast = new bootstrap.Toast(toastElement);
        toast.show();
    }

    // 表格行点击效果
    const tableRows = document.querySelectorAll('#logsTable tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('click', function() {
            // 移除其他行的选中状态
            tableRows.forEach(r => r.classList.remove('table-active'));
            // 添加当前行的选中状态
            this.classList.add('table-active');
        });
    });
});
</script>

<style>
.log-details {
    font-size: 0.85rem;
    max-width: 300px;
    word-break: break-word;
}

.table th {
    font-weight: 600;
    vertical-align: middle;
    background-color: #f8f9fa;
    border-bottom: 2px solid #e9ecef;
}

.table-hover tbody tr:hover {
    background-color: rgba(13, 110, 253, 0.05);
    cursor: pointer;
}

.table-active {
    background-color: rgba(13, 110, 253, 0.1) !important;
}

.badge {
    font-weight: 500;
    padding: 0.4em 0.65em;
    font-size: 0.75rem;
}

.form-label.small {
    font-size: 0.85rem;
}

.input-group-sm {
    font-size: 0.875rem;
}

.card-header {
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.stat-card {
    border-left: 4px solid var(--primary-color);
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

/* 响应式调整 */
@media (max-width: 768px) {
    .card-header {
        padding: 1rem;
    }

    .table-responsive {
        font-size: 0.875rem;
    }

    .badge {
        font-size: 0.7rem;
    }
}
</style>
{% endblock %}